/**
 * iframe 地址跳转
 * @param url
 */
function openHtml(url) {
    $("#layui-body #iframe").attr({"src":url});
    add_url(url)
}

/**
 * cide 验证码切换
 * @param url
 * @param elm
 */
function vifCode(url,elm) {
    $(elm).attr({"src":url})
}

/**
 *  给浏览器添加地址栏
 *  url要添加参数。获取最外部的window.修改href
 * 支持History API
 */
function add_url(url) {
    if (window.history && history.pushState){
        var tw = window.top;
        var twa =tw.location.href.split("#");
        var newUrl =  twa[0]+"#"+url;
        tw.history.replaceState(null,null,newUrl);
    }
}

/**
 * 清楚缓存
 * @param url
 * @param data
 */
function clearCache(url,data) {
    $.ajax({
        type:'get',
        dataType:'json',
        data:data,
        url:url,
        success:function (res) {
            layer.msg(res.msg);
        }
    })
}


/**
 * 推出系统
 * @param url
 * @param data
 */
function logout(url,data) {
    $.ajax({
        type:'get',
        dataType:'json',
        data:data,
        url:url,
        success:function (res) {
            layer.msg(res.msg);
            localStorage.removeItem('url_link');
            if(res.url){
                location.href = res.url;
            }
        }
    })
}

/**
 * 基于layui upload 文件上传 方法
 * @param elm 绑定上传元素 Id
 * @param url 上传地址
 * @param table 展示容器
 * @param multiple 是否开启多图上传，true / false
 */
function uploadFile(options){
    var upload = layui.upload;
    var param = {
        elm:'#test1',
        url:"",
        table:'.up-table',
        multiple:false,
        exts:'jpg|png|bmp|jpeg|avg',
        inputName:'file',
        success:'',
        err:''
    };
    if(options){
        param = options
    }
    if(typeof options.success === 'function'){
        param.success = options.success;
    }else {
        param.success = function(res){
            var str = '<tr>'+
                '<td>'+
                '<input type="text" class="layui-input" name="'+param.inputName+'" value="'+res.data[0]+'">'+
                '</td>'+
                '<td>'+
                '<img width="80"  src="'+res.data[0]+'">'+
                '</td>'+
                '<td>'+
                '<a href="javascript:;" class="layui-btn layui-btn-danger layui-btn-xs del-photos-btn">删除</a>'+
                '</td>'+
                '</tr>'
            if(param.multiple===false){
                $(param.table).find("tr").remove();
            }
            $(param.table).append(str);
            $(".del-photos-btn").click(function () {
                $(this).parents("tr").eq($(this).index()).remove()
            })
        }
    }
    if(typeof options.err === 'function'){
        param.success = options.err;
    }else {
        param.err = function(){
            layer.msg("请求异常")
        };
    }
    upload.render({
        elem: param.elm
        ,url: param.url
        ,multiple:param.multiple
        ,exts:param.exts
        ,done:param.success
        ,error:param.err
    });
    $(".del-photos-btn").click(function () {
        $(this).parents("tr").eq($(this).index()).remove()
    })
}

/**
 * 发送邮件
 */
function mailer(url) {
    layer.open({
        type:2,
        content:url,
        area:["600px","450px"]
    })
}

/**
 * 上传服务 替代 uploadFile 方法上传
 * @param opt
 */
function uploadFiles(opt) {
    var upload = layui.upload;
    var element= layui.element;
    //文件列表
    var fileList = [];
    //是否文件多传
    opt.multiple = opt.multiple? opt.multiple:true;
    //处理type
    opt.type     = opt.type?opt.type:2;
    //content
    opt.content  = opt.content?opt.content:''
    //云上传
    var restUpStatus = false;
    var obj = {
        //默认提供模板
        template:function () {
            var str = '<div class="up-container">'+
            '<div class="layui-tab layui-tab-brief" lay-filter="upTabs">'+
            '<ul class="layui-tab-title">'+
            '<li class="layui-this"  lay-id="1">上传文件</li>'+
            '<li  lay-id="2">网络文件</li>'+
            '<li  lay-id="3">上传到云存储</li>'+
            '</ul>'+
            '<div class="layui-tab-content" style="padding: 10px;">'+
            '<div class="layui-tab-item layui-show">'+
            '<div>'+
            '<button type="button" class="layui-btn uploadFileBtn">'+
            '<i class="layui-icon">&#xe67c;</i>上传图片'+
            '</button>'+
            '</div>'+
            '</div>'+
            '<div class="layui-tab-item">'+
            '<div>请输入网路地址</div>'+
            '<input type="text" class="layui-input" name="info[filename]" placeholder="http://">'+
            '</div>'+
            '<div class="layui-tab-item" id="cloud">'+
            // '<button type="button" class="layui-btn uploadFileBtn">'+
            // '<i class="layui-icon">&#xe67c;</i>上传图片'+
            //'</button>'+
            '</div>'+
            '</div>'+
            '</div>'+
            '<table class="layui-table upTable">'+ '</table>'+
            '</div>';
            return str;
        },
        //上传文件
        uploadFile:function () {
            //文件上传操作
            var uploadInst = upload.render({
                elem: '.uploadFileBtn'
                ,url: opt.upUrl
                ,multiple: opt.multiple,
                data:{
                    id: function(){
                        return $('input[name=id]').val();
                    }
                }
                //选择文件回调方法
                ,choose: function(obj){
                   // files = obj.pushFile();
                    obj.preview(function(index, file, result){
                        if($(".tr_"+index).length>0){
                            $(".tr_"+index).remove()
                        }
                            var tr = '<tr class="tr_'+index+'">'+
                            '<td>'+
                            '<div class="layui-col-md3 layui-col-sm3"><img src="'+result+'" alt="" width="110" height="110"></div>'+
                            '<div class="layui-col-md9 layui-col-sm9" >'+
                            '<div class="upLeftMsg" style="margin-top: 40px;">'+
                            '<span class="upTips">等待上传</span>'+
                            '<div class="layui-progress" lay-filter="upProgress">'+
                            '<div class="layui-progress-bar" lay-percent="0%"></div>'+
                            '</div>'+
                            '</div>'+
                            '</div>'+
                            '<input type="hidden" class="layui-input" value="'+index+'" name="id">'+
                            '</td>'+
                            '<td width="120">' +
                            '<a class="layui-btn layui-btn-danger layui-btn-xs deleteFileBtn">删除</a>'+
                            '<a class="layui-btn  layui-btn-xs restUploadBrn" style="display: none;">重新上传</a>'+
                            '</td>'+
                            '</tr>';
                        $('.upTable').append(tr)
                        $(".tr_"+index).find(".deleteFileBtn").click(function () {
                            $(this).parents('tr').remove()
                            fileList.splice($(this).index(),1);
                        });
                        $(".tr_"+index).find(".restUploadBrn").click(function () {
                            fileList.splice($(this).index(),1);
                            obj.upload(index, file);
                            restUpStatus = true
                        })

                    });
                }
                //多文件上传回调
                ,allDone: function(obj){

                }
                //成功后回调
                ,done: function(res,index,upload){
                    var el =  $(".tr_"+index);
                    if(res.code===1){
                        if(opt.multiple==true)
                        {
                            fileList.push(res.data)
                        }else {
                            fileList[0] = res.data
                        }
                        el.find(".restUploadBrn").hide();
                    }else{
                        fileList = [];
                        el.find(".restUploadBrn").show();

                    }
                    el.find(".upTips").text(res.msg);
                    //重传
                    if(restUpStatus && res.data.id){
                        $(".tr_"+res.data.id).find(".upTips").text(res.msg);
                    }
                }
                //选择文件之前回调
                ,before: function(obj){

                }
                //上传进度条
                ,progress: function(n, elem, res, index){
                    var percent = n + '%'
                    element.progress('upProgress', percent);
                    element.progress('upProgress-'+ index, n + '%');
                    $(".upTips").text("上传中.......");
                }
                //错误提示
                ,error: function( res,index, upload){
                    $(".tr_"+res).find(".upTips").text("上传失败");
                    $(".tr_"+res).find(".restUploadBrn").show();
                }
            });
        },
        //打开文件
        open:function () {
            var layerUp =layer.open({
                title:"文件上传",
                content:opt.type==2?opt.url:obj.template(),
                type:opt.type,
                area:["700px","500px"],
                offset: '100px',
                btn:["确定","取消"],
                success:function () {
                    element.on('tab(upTabs)', function(){
                        $(".upTable").html('')
                        var layId = this.getAttribute('lay-id');
                        if(layId == 2){
                            $("input[name='info[filename]']").change(function () {
                                fileList = $(this).val()
                            })
                        }else {
                            if(layId == 3) opt.url = opt.url+"?type=cloud";
                            obj.uploadFile()
                        }
                        if(layId==3 && opt.cloud){
                            $("#cloud").html('<iframe src="'+opt.cloud+'" style="width:100%;height: 300px;"></iframe>');
                        }
                        return false;
                    });
                    //obj.uploadFile()
                },
                yes:function () {
                    layer.close(layerUp);
                },
                end:function () {
                    //opt.file(fileList)
                    opt.file(localStorage.getItem("upload"))
                }
            })
        }
    }
    obj.open();
}


/**
 * 图片预览
 */
function imagePreviewDialog(path) {
    layer.photos({
        photos: {
            title:"",
            start: 0,
            data: [
                {
                    alt: "",
                    pid: 0,
                    src: path,
                    thumb: ""
                }
            ]
        }
        ,anim: 5
        ,shade:0.5
    });
}

/**
 * 图片压缩
 */
function compressImg(url){
    var loads = layer.load(1,{
        title:'压缩中',
        success:function () {
            $.ajax({
                type:'get',
                url:url,
                dataType:'json',
                success:function (res) {
                    layer.msg(res.msg)
                    if(res.code==1){
                        layer.close(loads)
                    }
                }
            })
        }
    });
}

/**
 * 保证数组值的唯一性
 * @param arr
 * @returns {Array}
 */
function unique(arr) {
    var result = [], hash = {};
    for (var i = 0, elem; (elem = arr[i]) != null; i++) {
        if (!hash[elem]) {
            result.push(elem);
            hash[elem] = true;
        }
    }
    return result;
}

/**
 * 消息队列
 */
function sendQueue(url) {
    layer.open({
        title:false,
        content:"请选择你所需要推送的账号类型",
        btn:["邮件","短信","公众号"],
        yes:function(index,layero){
            push('email')
        },
        btn2:function (index,layero) {
            push('sms')
        },
        btn3:function (index,layero) {
            push('official_accounts')
        },
    });
    function push(type) {
        $.ajax({
            type:"post",
            url:url,
            data:{
                type:type
            },
            dataType:'json',
            success:function (res) {
                layer.msg(res.msg)
            },
            error:function(err){
                layer.msg("网络错误请稍后再试")
            }
        })
    }
}